/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue'
import Router from 'vue-router'
import ElementUI from 'element-ui';

import Main from '@/views/main'
import MainContent from '@/views/main-content'
import Article from '@/views/content/article'
import Publish from "@/views/content/publish"
import SearchPage from '@/views/content/search-page'
import UserPage from '@/views/content/user-page'

Vue.use(Router)

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new Router({
  mode: 'history',  //去掉url中的#
  routes: [
    {
      path: '/', component: Main,
      children: [{
        name: 'main-content',
        path: '/main-content',
        component: MainContent
      },
      {
        name: 'article',
        path: '/article',
        component: Article
      },
      {
        name: 'publish',
        path: '/publish',
        component: Publish,
        beforeEnter: (to, from, next) => {
          var userJsonStr = sessionStorage.getItem("user");
          if (userJsonStr != null) {
            next();
          } else {
            ElementUI.Message.warning('发布文章前请先登录');
          }
        }
      },
      {
        name: 'search-page',
        path: '/search-page',
        component: SearchPage
      },
      {
        name: 'user-page',
        path: '/user-page',
        component: UserPage
      }]
    },
    // { path: '/Login', component: Login },
    // { path: '/Home', component: Home },
    // { path: '/Register', component: Register },
    // { path: '/Newnote/:id', component: Newnote, meta: { requireAuth: true } },
    // { path: '/Myblog', component: Myblog, meta: { requireAuth: true } },
    // { path: '/Articledetails/:id', component: Articledetails, meta: { requireAuth: true } }  //文章详情路由接收文章id参数
  ],
  linkActiveClass: 'ivu-menu-item-active'
})

//配置全局路由守卫验证路由是否需要登录
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuth)) { // 判断该路由是否需要登录权限
    if (JSON.parse(sessionStorage.getItem("islogin")) != false && JSON.parse(sessionStorage.getItem("islogin")) != null) { // 判断当前是否登录
      next(); //如果登录了next()就表示允许跳转到要去的路由
    }
    else { //否则就跳转到下面的登录界面
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  }
  else {  //如果该路由不需要登录验证就直接允许跳转
    next();
  }
});

export default router